package com.soulless.mybatis.ext;

import org.mybatis.generator.api.GeneratedJavaFile;
import org.mybatis.generator.api.IntrospectedTable;
import org.mybatis.generator.api.PluginAdapter;
import org.mybatis.generator.api.dom.java.*;
import org.mybatis.generator.api.dom.xml.Attribute;
import org.mybatis.generator.api.dom.xml.XmlElement;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zenglei
 * @Description 功能描述
 * @date 2020/11/17 14:32
 */
public class GeneratorMapperPlugin extends PluginAdapter {

    public boolean validate(List<String> warnings) {
        return true;
    }

    @Override
    public List<GeneratedJavaFile> contextGenerateAdditionalJavaFiles(IntrospectedTable introspectedTable) {
        List<GeneratedJavaFile> generatedJavaFiles = introspectedTable.getGeneratedJavaFiles();
        List<GeneratedJavaFile> answer = new ArrayList<>();
//        String targetProject = context.getJavaClientGeneratorConfiguration().getTargetProject();
//        String targetPackage = context.getJavaClientGeneratorConfiguration().getTargetPackage();
        for (int i = 0; i < generatedJavaFiles.size(); i++) {
            GeneratedJavaFile jf = generatedJavaFiles.get(i);
            String targetPackage = jf.getTargetPackage();
            String targetProject = jf.getTargetProject();
            System.out.println("zzzzz targetPackage zzzzzzz  " + targetPackage);
            System.out.println("zzzzz targetProject zzzzzzz  " + targetProject);
            System.out.println("zzzzz getFileName zzzzzzz  " + jf.getFileName());
            // 判断是否存在该文件
            if (isNotExists(targetProject + "." + targetPackage, jf.getFileName() + ".java")) {
                answer.add(jf);
            }
        }
        return answer;
    }

    /**
     * 判断文件是否存在，不存在返回true
     *
     * @param path
     * @param fileName
     * @return
     */
    private boolean isNotExists(String path, String fileName) {
        String bn = System.getProperty("user.dir");
        String file = bn + "." + path;
        String pathName = file.replace(".", "/").replace("\\", "/") + "/" + fileName;
        File f = new File(pathName);
        return !f.exists();
    }

    private void getAttribute(XmlElement xmlElement, String name, String value) {
        xmlElement.addAttribute(new Attribute(name, value));
    }
}
